package org.jbox2d.testbed.tests;

import org.jbox2d.collision.shapes.CircleDef;
import org.jbox2d.collision.shapes.PolygonDef;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.joints.RevoluteJointDef;
import org.jbox2d.testbed.*;

import processing.core.PImage;

public class MyTest extends AbstractExample
{
	private boolean firstTime=true;

	public MyTest(TestbedMain parent)
	{
		super(parent);
	}

	@Override
	public void create()
	{
		if(firstTime)
		{
			firstTime=false;
			setCamera(0f, 12f, 1f);
			settings.hz=60;
			settings.iterationCount=10;
		}
		
		Body pivotPoint=null;
		
		{
			PolygonDef groundDef=new PolygonDef();
			groundDef.setAsBox(200, 2);
			
			BodyDef groundBodyDef=new BodyDef();
			groundBodyDef.position=new Vec2(0f,0f);
			m_world.createBody(groundBodyDef).createShape(groundDef);
			
			PolygonDef pivotPointDef=new PolygonDef();
			pivotPointDef.setAsBox(0.1f, 0.1f);
			
			BodyDef pivotPointBodyDef=new BodyDef();
			pivotPointBodyDef.position=new Vec2(-115.5f,0f);
			pivotPoint=m_world.createBody(pivotPointBodyDef);
			pivotPoint.createShape(pivotPointDef);
		}
		
		{
			for(int i=0;i<7;++i)
			{
				PolygonDef toyDef=new PolygonDef();
				toyDef.setAsBox(1f, 1f);
				toyDef.density=.1f;
				toyDef.restitution=1f;
				
				BodyDef toyBodyDef=new BodyDef();
				toyBodyDef.position.set(0,2.5f+i*2);
				
				Body toyBody=m_world.createBody(toyBodyDef);
				//toyBody.setLinearVelocity(new Vec2(0,0f));
				toyBody.createShape(toyDef);
				toyBody.setMassFromShapes();
				
				PImage image=parent.loadImage("exp3.png");
				bindImage(image, new Vec2(0, 0), 0, 1.9f/image.width, toyBody);			
			}
			
			RevoluteJointDef jd = new RevoluteJointDef();
			Body prevBody=pivotPoint;
			
			for(int i=0;i<5+1;++i)
			{
				Body toyBody=null;
				if(i!=5)
				{
					PolygonDef toyDef=new PolygonDef();
					toyDef.setAsBox(.5f, 1.2f);
					toyDef.density=20f;
					toyDef.friction=1f;
					toyDef.restitution=1f;
					
					BodyDef toyBodyDef=new BodyDef();
					toyBodyDef.position.set(-115f+i,15f-i);
					toyBodyDef.angle=MathUtils.PI/4;
					
					toyBody=m_world.createBody(toyBodyDef);
					//toyBody.setLinearVelocity(new Vec2(0,0f));
					toyBody.createShape(toyDef);
					toyBody.setMassFromShapes();
				}
				else toyBody=pivotPoint;
				
				Vec2 anchor=new Vec2(-115.5f+i,15.5f-i);
				jd.initialize(prevBody, toyBody, anchor);
				m_world.createJoint(jd);
				
				prevBody=toyBody;
			}
			
			
		}
	}
	
	@Override
	public String getName() {
		return "MyTest";
	}
}
